# -*- coding: utf-8 -*-

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "少儿重大疾病保险"

    def genProductInfo(self):
        planI = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["300000"],
                # 防癌医疗保险
                "defineCancer": ["200000"],
                # 一般住院津贴
                "generalHospital": ["80/天"],
                # 癌症住院津贴
                "cancerHospital": ["100/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["全面款"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["200000"],
                # 防癌医疗保险
                "defineCancer": ["200000"],
                # 一般住院津贴
                "generalHospital": ["80/天"],
                # 癌症住院津贴
                "cancerHospital": ["100/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["热销款"]
            }
        }

        for k in planI:
            for v in product(planI[k]["year"], planI[k]["gender"], planI[k]["expire"], planI[k]["payType"],
                             planI[k]["childrenDisease"], planI[k]["defineCancer"], planI[k]["generalHospital"],
                             planI[k]["cancerHospital"], planI[k]["operationHospital"], planI[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))

        planII = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["50000"],
                # 防癌医疗保险
                "defineCancer": ["0", "50000", "100000", "200000"],
                # 一般住院津贴
                "generalHospital": ["0"],
                # 癌症住院津贴
                "cancerHospital": ["0"],
                # 住院手术津贴
                "operationHospital": ["0"],
                # 产品计划
                "plan": ["自定义"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["100000", "150000", "200000", "250000", "300000"],
                # 防癌医疗保险
                "defineCancer": ["0", "50000", "100000", "200000"],
                # 一般住院津贴
                "generalHospital": ["0"],
                # 癌症住院津贴
                "cancerHospital": ["0"],
                # 住院手术津贴
                "operationHospital": ["0"],
                # 产品计划
                "plan": ["自定义"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["100000", "150000", "200000", "250000", "300000"],
                # 防癌医疗保险
                "defineCancer": ["0", "50000", "100000", "200000"],
                # 一般住院津贴
                "generalHospital": ["30/天"],
                # 癌症住院津贴
                "cancerHospital": ["50/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["自定义"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["100000", "150000", "200000", "250000", "300000"],
                # 防癌医疗保险
                "defineCancer": ["0", "50000", "100000", "200000"],
                # 一般住院津贴
                "generalHospital": ["50/天"],
                # 癌症住院津贴
                "cancerHospital": ["80/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["自定义"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 少儿重大疾病
                "childrenDisease": ["100000", "150000", "200000", "250000", "300000"],
                # 防癌医疗保险
                "defineCancer": ["0", "50000", "100000", "200000"],
                # 一般住院津贴
                "generalHospital": ["80/天"],
                # 癌症住院津贴
                "cancerHospital": ["100/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["自定义"]
            }
        }

        for k in planII:
            for v in product(planII[k]["year"], planII[k]["gender"], planII[k]["expire"], planII[k]["payType"],
                             planII[k]["childrenDisease"], planII[k]["defineCancer"], planII[k]["generalHospital"],
                             planII[k]["cancerHospital"], planII[k]["operationHospital"], planII[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):
        if dt["plan"] == "自定义":
            print("\n/*~~~~~~自定义~~~~~~~*/")

            if dt["gender"] == "M":
                sex = {
                    "woman":0,
                    "man":1
                }
            else:
                sex = {
                    "woman": 1,
                    "man": 0
                }

            data = {"planClass": 2, "amountFormList": [
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 300000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 200000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"childrenIll": dt["childrenDisease"], "cancerDisease":dt["defineCancer"] , "generalAllowance": "0" if dt["generalHospital"] == "0" else dt["generalHospital"].replace("/天", ""), "cancerAllowance":"0" if dt["cancerHospital"] == "0" else dt["cancerHospital"].replace("/天", ""),
                 "hospitalAllowance": dt["operationHospital"]}], "beginDate": "2020-03-17", "birthDate": "{0}-03-05".format( str(2020-int(dt["year"]))),
                    "insurantManNum": sex["man"], "insurantWomanNum":sex["woman"]}
            payload = json.dumps(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult3"]["originalPremium"]
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }

                self.mysql.updatePrice(data)
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }

                self.mysql.updateTask(data)
                print("\n/*产品价格更新失败:%d*/" % dt["id"])
        elif dt["plan"] == "全面款":
            if dt["gender"] == "M":
                sex = {
                    "woman":0,
                    "man":1
                }
            else:
                sex = {
                    "woman": 1,
                    "man": 0
                }

            print("\n/*~~~~~~全面款~~~~~~~*/")
            data = {"planClass": 0, "amountFormList": [
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 300000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 200000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"childrenIll": "150000", "cancerDisease": "0", "generalAllowance": "0", "cancerAllowance": "0",
                 "hospitalAllowance": "0"}], "beginDate": "2020-03-17",
                    "birthDate": "{0}-03-05".format(str(2020 - int(dt["year"]))), "insurantManNum": sex["man"],
                    "insurantWomanNum": sex["woman"]}
            payload = json.dumps(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)


            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult1"]["originalPremium"]
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }


                self.mysql.updatePrice(data)
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }

                self.mysql.updateTask(data)
                print("\n/*产品价格更新失败:%d*/" % dt["id"])
        else:
            print("\n/*~~~~~~热销款~~~~~~~*/")
            if dt["gender"] == "M":
                sex = {
                    "woman":0,
                    "man":1
                }
            else:
                sex = {
                    "woman": 1,
                    "man": 0
                }

            data = {"planClass": 1, "amountFormList": [
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 300000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"cancerAllowance": "100", "cancerDisease": 200000, "childrenIll": 200000, "generalAllowance": "80",
                 "hospitalAllowance": "5000"},
                {"childrenIll": "150000", "cancerDisease": "0", "generalAllowance": "0", "cancerAllowance": "0",
                 "hospitalAllowance": "0"}], "beginDate": "2020-03-17",
                    "birthDate": "{0}-03-05".format(str(2020 - int(dt["year"]))), "insurantManNum": sex["man"],
                    "insurantWomanNum": sex["woman"]}

            payload = json.dumps(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult2"]["originalPremium"]
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                self.mysql.updatePrice(data)
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }

                self.mysql.updateTask(data)
                print("\n/*产品价格更新失败:%d*/" % dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

